window.yx = {
	//封装原生的dom方法, 不用写太长的方法名
	g:function(name){
		return document.querySelector(name)
	},
	ga:function(name){
		return document.querySelectorAll(name)
	},
	
	//封装一个 添加 事件监听 的方法
	addEvent: function(obj, ev, fn){ //obj：dom元素  ev：事件名称 fn：事件回调
		if(obj.addEventListener){  //兼容性处理
			obj.addEventListener(ev, fn)
		}else{
			obj.attachEvent('on'+ev, fn)
		}
	},
	//封装一个 移除 事件监听 的方法
	removeEvent: function(obj, ev, fn){
		if(obj.removeEventListener){
			obj.removeEventListener(ev, fn)
		}else{
			obj.detachEvent('on'+ev, fn)
		}
	},
	
	//工具方法，获取某个元素距离html顶部的距离。
	getTopValue: function(obj){
		/* 
		//累计计算有bug
		var top = 0
		while(obj.offsetParent){
			top += obj.offsetTop
			obj = obj.offsetParent
		}
		return top */
		
		return obj.getBoundingClientRect().top + window.pageYOffset
		//return obj.getBoundingClientRect().top + document.documentElement.scrollTop
	},
	
	format: function(v){  //给时间补0
		return v<10 ? '0'+v : v;
	},
	
	cutTime: function(target){ //倒计时
		var currentDate = new Date();
		var v = Math.abs(target-currentDate);
		return {
				d: parseInt(v/(24*3600000)),
				h: parseInt(v%(24*3600000)/3600000),
				m: parseInt(v%(24*3600000)%3600008/60000),
				s: parseInt(v%(24*3600000)%3600000%60000/1000)
		};
	},
	
	//时间格式化方法
	formatDate: function(time){
		var d = new Date(time)
		return d.getFullYear() + '-' + yx.format(d.getMonth()+1) + '-' + 
			yx.format(d.getDate()) + ' ' + yx.format(d.getHours()) + ':' + yx.format(d.getMinutes()) 
			
	},
	
	//解析URL 
	parseURL: function(url){  //把url后面的参数解析成对象
		var reg = /(\w+)=(\w+)/ig
		var result = {}
		url.replace(reg, function(a, b, c){
			result[b] = c
		})  
		return result
	},
	
	//存放各种公共功能的方法，方便于在各个页面进行复用
	public: {
		
		//1 吸顶功能、弹出二级菜单功能
		navFn: function(){
			var nav = yx.g(".nav")
			var list = yx.ga(".nav .navBar li") //一级菜单 
			var subNav = yx.g(".subNav")
			var uls = yx.ga(".subNav ul") //二级菜单 
			var newList = []  //存储 有二级菜单的 一级菜单
			
			//根据索引值，过滤掉没有二级菜单的一级菜单
			//第一个和最后三个li没有hover状态，所以需要过滤掉
			for(var i=1; i<list.length-3; i++){
				newList.push(list[i])
			}
			
			for(var i=0; i<newList.length; i++){
				newList[i].index = uls[i].index = i  //添加索引
				
				//鼠标移入
				newList[i].onmouseenter = uls[i].onmouseenter = function(){ 	
					
					newList[this.index].className = 'active'  //添加 激活样式
					
					//subNav.style.display = "block"  //没有淡入淡出效果
					//uls[this.index].style.display = 'block'
					
					subNav.style.opacity = 1  //有淡入淡出效果
					subNav.style.visibility = "visible" 
					uls[this.index].style.display = 'block'
				}
				
				//鼠标移出
				newList[i].onmouseleave = uls[i].onmouseleave = function(){ 
					
					newList[this.index].className = ''
					/* subNav.style.display = "none"
					uls[this.index].style.display = 'none' */
					
					subNav.style.opacity = 0
					subNav.style.visibility = "hidden" 
					uls[this.index].style.display = 'none'  
				}
			}
			
			var offsetTop = nav.offsetTop  //保存起来
			//吸顶导航
			function fixedTop(){
				
				/* if(window.pageYOffset > nav.offsetTop){
					nav.id = "navFix"
				}else{
					nav.id = ""
				} */
				//console.log(window.pageYOffset, nav.offsetTop)
				//简写
				if(window.pageYOffset > offsetTop){
					nav.id = "navFix"
				}else{
					nav.id = ""
				}
				
			}
			fixedTop()
			yx.addEvent(window, 'scroll', fixedTop)
		},
		
		//2 图片懒加载功能
		lazyLoadImg: function(){
			var imgs = yx.ga('.original')  //获取所有需要懒加载的img标签 
			//var n = 0  
			
			function delayImg(){
					var scrollTop = window.innerHeight + window.pageYOffset  //屏幕可视区域高度 + 滚动条滚动距离
						//如果图片离html的上边的距离小于滚动条的距离与可视区的距离之和的话就表示图片已经进入到可视区了
						for(var i=0; i<imgs.length; i++){
							
							if(yx.getTopValue(imgs[i]) < scrollTop){
								
								imgs[i].src = imgs[i].getAttribute("data-src")
								//img标签换成真实地址后，就可以去掉懒加载的类样式了
								imgs[i].removeAttribute('class')
								//n ++
							}
						}
						//判断：当页面最后一张图片的src换成真实地址后，就不需要监听scroll事件了
						
						if(imgs[imgs.length-1].getAttribute('src') !== "images/empty.gif"){
							yx.removeEvent(window, 'scroll', delayImg)
						} 
						
					 
					/* if(n === imgs.length){
						 yx.removeEvent(window, 'scroll', delayImg)
					 } */
			}
			
			delayImg()
			yx.addEvent(window,'scroll', delayImg)
		},
		
		//3.回到顶部功能
		backPageTop: function(){
			var backBtn = yx.g(".back")
			var timer
			backBtn.onclick = function(){
				if(timer){
					clearInterval(timer)
				}
				var scrollTop = window.pageYOffset  //当前滚动条滚动距离
				timer = setInterval(function(){
					scrollTop -= 150
					if(scrollTop<=0){
						scrollTop = 0
						clearInterval(timer)
					}
					window.scrollTo(0, scrollTop)
				}, 16)
			}
		},
		
		//4.购物车功能
		cartFn: function(){
			//4.0 点击购物车图标 显示/隐藏 商品列表
			var cartWrap = yx.g(".nav .cartWrap")
			var contentWrap1 = yx.g(".nav .cartWrap .cart") //商品列表和滚动条 父级
			cartWrap.onclick = function(){  //购物车图标 点击事件
				
				contentWrap1.style.display = contentWrap1.style.display === 'block' ? 'none' : 'block'
				
				contentWrap1.onclick = function(ev){
					ev.stopPropagation()
					return false
				}
				
				if(contentWrap1.style.display === 'block'){
					scrollFn()
				}
				
			}
			
			//更新滚动条
			scrollFn()
			//4.1 自定义滚动条功能
			function scrollFn(){
				var contentWrap = yx.g(".nav .cartWrap .list") //商品列表和滚动条 父级
				var content = yx.g(".nav .cartWrap .list ul")  //商品列表 
				var scrollBar = yx.g(".nav .cartWrap .list .scrollBar")  //滚动条
				var slideWrap = yx.g(".nav .cartWrap .list .scrollBar .swideWrap")  //滚动条 滑块 父级
				var slide = yx.g(".nav .cartWrap .list .scrollBar .slide")  //滚动条 滑块
				var btns = yx.ga(".nav .cartWrap .list .scrollBar span")  //滚动条 按钮
				var timer
				
				//滑块高度 倍数
				var multiple = content.offsetHeight/contentWrap.offsetHeight
				//倍数上限
				if(multiple>20){
					multiple = 20
				}
				
				//是否显示滚动条
				scrollBar.style.display = multiple<=1 ? 'none' : 'block'
				
				//设置滑块的高度
				slide.style.height = slideWrap.offsetHeight/multiple + 'px'
				
				var scrollTop = 0  //滚动条 要走的距离
				var maxHeight = slideWrap.offsetHeight - slide.offsetHeight  //滑块能够走的最大距离
				//console.log(slideWrap.offsetHeight, slide.offsetHeight)
				
				//滑块主体功能
				slide.onmousedown = function(ev){
					clearInterval(timer)
					var disY = ev.clientY - slide.offsetTop
					document.onmousemove = function(ev){
						scrollTop = ev.clientY - disY
						scroll()
					}
					document.onmouseup = function(){
						this.onmousemove = null
					}
					ev.cancelBubble = true  //阻止冒泡
					return false //阻止默认事件
				}
				
				//滚动方法
				function scroll(){
					if(scrollTop<0){  //不能向上超出
						scrollTop = 0
					}else if(scrollTop>maxHeight){ //不能向下超出
						scrollTop = maxHeight
					}
					
					var scaleY = scrollTop/maxHeight  //比例值 = 走的距离/最大可走距离
					
					slide.style.top = scrollTop + 'px'  //设置滑块位置
					content.style.top = -(content.offsetHeight-contentWrap.offsetHeight)*scaleY + 'px'
				}
				
				//滚轮功能
				function mouseScroll(obj, fnUp, fnDown){
					obj.onmousewheel = fn
					obj.addEventListener('DOMMouseScroll', fn)
					function fn(ev){
						if(ev.wheelDelta>0 || ev.detail<0){ //滚轮往上滚
							fnUp.call(obj)
						}else{ //滚轮往下滚
							fnDown.call(obj)
						}
						ev.preventDefault()
						return false
					}
				}
				
				mouseScroll(contentWrap, function(){
					scrollTop -= 10
					scroll()
					clearInterval(timer)
				}, function(){
					scrollTop += 10
					scroll()
					clearInterval(timer)
				})
				
				//上下箭头功能
				for(var i=0; i<btns.length; i++){
					btns[i].index = i 
					btns[i].onmousedown = function(){
						clearInterval(timer)
						var n = this.index
						timer = setInterval(function(){
							scrollTop = n ? scrollTop+5 : scrollTop-5
							scroll()
						}, 16)
					}
					btns[i].onmouseup = function(){
						clearInterval(timer)
					}
				}
				
				//滚动条点击功能
				slideWrap.onmousedown = function(ev){
					clearInterval(timer)
					timer = setInterval(function(){
						var slideTop = slide.getBoundingClientRect().top + slide.offsetHeight/2 
						
						if(ev.clientY<slideTop){
							//这个条件成立说明现在鼠标在滑块的上面，滚动条应该往上走
							scrollTop -= 5
						}else{
							scrollTop += 5
						}
						
						//如果他们俩的差的绝对值小于5了，我就认为到达了终点，这个时候清除掉定时器,
						//就能够解决闪动的问题
						if(Math.abs(ev.clientY-slideTop) <= 5){
							clearInterval(timer)
						}
						
						scroll()
					}, 16)
				}
				
			}
		
			//4.2 本地存储功能
			//4.2.1 渲染 本地存储 商品数据
			var productNum = 0  //购物车中的商品数量
			;(function(localStorage){
				var totalPrice = 0;  //商品合计
				var ul = yx.g(".nav .cart ul")
				var str = ''
				
				//渲染 商品列表 
				ul.innerHTML = 0
				for(var i=0; i<localStorage.length; i++){
					var attr = localStorage.key(i)  //取到每个key
					var value = JSON.parse(localStorage[attr])  //取到每个value
					
					if(value && value.sign === "productLocal"){  //筛选localStorage 避免拿到其它数据
						//根据数据 生成 html字符串
						str += '<li data-id = "'+ value.id +'">' + 
										'<a href="#" class="product-pic"><img src="'+ value.img +'" ></a>' + 
										'<div class="message">' + 
											'<p><a href="#">'+ value.name +'</a></p>' + 
											'<p>'+ value.specs.join(" ") + ' x ' + value.num + '</p>' + 
										'</div>' + 
										'<div class="price">￥'+ value.price +'</div>' + 
										'<div class="close">X</div>' + 
									'</li>'
									
						//计算 商品合计
						totalPrice += parseFloat(value.price) * value.num
					}
				}
				ul.innerHTML = str
						
				//渲染 商品总数
				productNum = ul.children.length
				yx.g(".nav .cartWrap>i").innerHTML = productNum
				
				//渲染 商品合计
				yx.g(".nav .cartWrap .total span").innerHTML = '￥' + totalPrice + '.00'
				
				//处理购物车为空的情况
				if(localStorage.length === 0){
					yx.g(".nav .cart .list ul").innerHTML = '暂无商品，赶紧去选购吧！'
						yx.g(".nav .cart .list ul").className = 'noGoods'
				}else{
					yx.g(".nav .cart .list ul").className = ''
				}
				
				//4.2.2 购物车 删除商品 功能
				var closeBtns = yx.ga(".nav .cart .close")
				for(var i=0; i<closeBtns.length; i++){
					closeBtns[i].onclick = function(){  //X号 点击事件
						//删除localStorage中的商品数据
						localStorage.removeItem(this.parentNode.getAttribute("data-id"))
						
						//更新页面
						yx.public.cartFn()
					}
				}
				
			})(localStorage);
		},
	
	}
}

